import React, { useReducer } from 'react'

const initalState = {
    count: 0,
    msg: 'atguigu'
}
/**
 * action :
 *    type: 动作类型
 */
function reducer(state, action) {
    switch (action.type) {
        case 'add':
            console.log('add case');
            // return什么，最新的state就是什么，所以为了不丢失其他数据，需要先解构state
            return {
                ...state,
                count: state.count + (action.payload ? action.payload : 1)
            }
        case 'dec':
            return {
                ...state,
                count: state.count - 1
            }
        case 'joinJian':
            return {
                ...state,
                msg: state.msg + '-'
            }
        default:
            throw new Error('没有匹配的action');
    }
}
export default function App() {
    // let [count, setCount] = useState(0);
    // let [msg, setMsg] = useState('atguigu');
    
    let [state, dispatch] = useReducer(reducer, initalState)
    console.log('state: ',state);
    return (
        <div>
            <p>count: {state.count}</p>
            <p>msg: {state.msg}</p>
            <p><button onClick={()=>{
                dispatch({type:'add',payload:2});// 触发reducer函数中的add 的case执行
            }}>count++</button></p>

            <p><button onClick={()=>{
                dispatch({type:'joinJian'})
            }}>msg --</button></p>
        </div>
    )
}
